package com.jeethink.web.controller.teach;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import com.aliyun.oss.ServiceException;
import com.jeethink.common.exception.oss.OssException;
import com.jeethink.common.utils.file.FileUtilss;
import com.jeethink.framework.util.ShiroUtils;
import com.jeethink.system.domain.SysOss;
import com.jeethink.system.service.ISysOssService;
import com.jeethink.system.service.ISysUserService;
import com.jeethink.teach.domain.TeachCommonFile;
import com.jeethink.teach.param.TeachPersonalDocumentsParam;
import com.jeethink.web.controller.system.cloud.CloudStorageService;
import com.jeethink.web.controller.system.cloud.OSSFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.jeethink.common.annotation.Log;
import com.jeethink.common.enums.BusinessType;
import com.jeethink.teach.domain.TeachPersonalDocuments;
import com.jeethink.teach.service.ITeachPersonalDocumentsService;
import com.jeethink.framework.web.base.BaseController;
import com.jeethink.common.page.TableDataInfo;
import com.jeethink.common.base.AjaxResult;
import com.jeethink.common.utils.poi.ExcelUtil;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 个人文件 信息操作处理
 *
 * @author jeethink
 * @date 2022-09-04
 */
@Controller
@RequestMapping("/teach/teachPersonalDocuments")
public class TeachPersonalDocumentsController extends BaseController {
    private String prefix = "teach/teachPersonalDocuments";

    @Autowired
    private ITeachPersonalDocumentsService teachPersonalDocumentsService;

    @Resource
    private ISysOssService sysOssService;

    @Resource
    private ISysUserService userService;

    @RequiresPermissions("teach:teachPersonalDocuments:view")
    @GetMapping()
    public String teachPersonalDocuments() {
        return prefix + "/teachPersonalDocuments";
    }

    /**
     * 查询个人文件列表
     */
    @RequiresPermissions("teach:teachPersonalDocuments:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TeachPersonalDocumentsParam param) {
        startPage();
        int userno = ShiroUtils.getUserId().intValue();
        String roleNo = userService.selectUserRoleGroup2(new Long((long)userno));
        if ("5".equals(roleNo)|| "6".equals(roleNo) || "7".equals(roleNo) || "8".equals(roleNo) || "11".equals(roleNo)){
            Long deptId = ShiroUtils.getSysUser().getDeptId();
            param.setDeptId(deptId);
        }
        List<TeachPersonalDocuments> list = teachPersonalDocumentsService.selectTeachPersonalDocumentsList(param);
        return getDataTable(list);
    }


    /**
     * 新增个人文件
     */
    @GetMapping("/add")
    public String add() {
        String loginName = ShiroUtils.getLoginName();
        if (StrUtil.equalsIgnoreCase(loginName,"admin")){
            return prefix + "/adminAdd";
        }else {
            return prefix + "/add";
        }
    }

    /**
     * 新增保存个人文件
     */
    @RequiresPermissions("teach:teachPersonalDocuments:add")
    @Log(title = "个人文件", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestParam("file") MultipartFile file, TeachPersonalDocuments teachPersonalDocuments)throws Exception {
        if (file.isEmpty()) {
            throw new OssException("上传文件不能为空");
        }
        String createBy ;
        if (StrUtil.isNotBlank(teachPersonalDocuments.getCreateBy())){
            createBy = teachPersonalDocuments.getCreateBy();
        }else {
            createBy=ShiroUtils.getLoginName();
        }

        // 上传文件
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        CloudStorageService storage = OSSFactory.build();
        String url = storage.uploadSuffix(file.getBytes(), suffix);
//        TeachCommonFile teachCommonFile = new TeachCommonFile();
        teachPersonalDocuments.setFileUrl(url);
        teachPersonalDocuments.setFileSuffix(suffix);
        teachPersonalDocuments.setCreateBy(createBy);
        teachPersonalDocuments.setFileName(fileName);
        teachPersonalDocuments.setCreateTime(new Date());
        teachPersonalDocuments.setFileSize(Double.valueOf(file.getSize()));
        teachPersonalDocuments.setDownloadTimes(0L);

        // 保存文件信息
        SysOss ossEntity = new SysOss();
        ossEntity.setUrl(url);
        ossEntity.setFileSuffix(suffix);
        ossEntity.setCreateBy(createBy);
        ossEntity.setFileName(fileName);
        ossEntity.setCreateTime(new Date());
        ossEntity.setService(storage.getService());
        sysOssService.save(ossEntity);

        return toAjax(teachPersonalDocumentsService.insertTeachPersonalDocuments(teachPersonalDocuments));
    }

    /**
     * 图片预览
     * @param id
     * @param mmap
     * @return
     */
    @GetMapping("/preview/{id}")
    public String resetPwd(@PathVariable("id") Long id, ModelMap mmap)
    {
        mmap.put("teachPersonalDocuments", teachPersonalDocumentsService.selectTeachPersonalDocumentsById(id));
        return prefix + "/preview";
    }

    @PostMapping("/previewClose")
    @ResponseBody
    public AjaxResult previewClose(TeachCommonFile teachCommonFile) {
        return success("");
    }

    @Log(title = "个人文件", businessType = BusinessType.UPDATE)
    @GetMapping("/downloadFile")
    public void downloadFile(Long id, HttpServletResponse response) throws IOException {
        TeachPersonalDocuments teachPersonalDocuments =teachPersonalDocumentsService.selectTeachPersonalDocumentsById(id);
        if (ObjectUtil.isNull(teachPersonalDocuments)) {
            throw new ServiceException("文件数据不存在!");
        }
        response.reset();
        FileUtilss.setAttachmentResponseHeader(response, teachPersonalDocuments.getFileName());
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE + "; charset=UTF-8");
        long data;
        try {
            data = HttpUtil.download(teachPersonalDocuments.getFileUrl(), response.getOutputStream(), false);
        } catch (HttpException e) {
            if (e.getMessage().contains("403")) {
                throw new ServiceException("无读取权限, 请在对应的OSS开启'公有读'权限!");
            } else {
                throw new ServiceException(e.getMessage());
            }
        }
        Long downloadTimes = teachPersonalDocuments.getDownloadTimes();
        if (downloadTimes == null){
            teachPersonalDocuments.setDownloadTimes(1L);
        }else {
            teachPersonalDocuments.setDownloadTimes((long) NumberUtil.add(teachPersonalDocuments.getDownloadTimes().intValue(),1));

        }
        teachPersonalDocumentsService.updateDownloadTimes(teachPersonalDocuments);
        response.setContentLength(Convert.toInt(data));
    }

    /**
     * 修改个人文件
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        TeachPersonalDocuments teachPersonalDocuments =teachPersonalDocumentsService.selectTeachPersonalDocumentsById(id);
        mmap.put("teachPersonalDocuments", teachPersonalDocuments);
        return prefix + "/edit";
    }

    /**
     * 修改保存个人文件
     */
    @RequiresPermissions("teach:teachPersonalDocuments:edit")
    @Log(title = "个人文件", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TeachPersonalDocuments teachPersonalDocuments) {
        teachPersonalDocuments.setUpdateBy(ShiroUtils.getLoginName());
        teachPersonalDocuments.setUpdateTime(new Date());
        return toAjax(teachPersonalDocumentsService.updateTeachPersonalDocuments(teachPersonalDocuments));
    }

    /**
     * 删除个人文件
     */
    @RequiresPermissions("teach:teachPersonalDocuments:remove")
    @Log(title = "个人文件", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(teachPersonalDocumentsService.deleteTeachPersonalDocumentsByIds(ids));
    }

}
